package com.gedmanager.qrcode;

import java.io.File;
import java.io.FileOutputStream;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRCodeGenerator {

	public static void createQRCodeImage(String fileName, String content) {
     
        QRCodeWriter writer = new QRCodeWriter();
        try {
            BitMatrix matrix = writer.encode(
            		content, BarcodeFormat.QR_CODE, 128, 128);
            // Now what?? 	
            
           
            File tosave = new File(fileName);

			FileOutputStream fOut;
			try {
				fOut = new FileOutputStream(tosave);
				toBitmap(matrix).compress(Bitmap.CompressFormat.PNG, 100, fOut);
				fOut.flush();
				fOut.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d("qrcode","falha " + e.getMessage());
				e.printStackTrace();
			}

			
			
        } catch (WriterException e) {
        	Log.d("qrcode","falha " + e.getMessage());
            e.printStackTrace();
        }
        

	}
	
	/**
	 * Writes the given Matrix on a new Bitmap object.
	 * @param matrix the matrix to write.
	 * @return the new {@link Bitmap}-object.
	 */
	public static Bitmap toBitmap(BitMatrix matrix){
	    int height = matrix.getHeight();
	    int width = matrix.getWidth();
	    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
	    for (int x = 0; x < width; x++){
	        for (int y = 0; y < height; y++){
	            bmp.setPixel(x, y, matrix.get(x,y) ? Color.BLACK : Color.WHITE);
	        }
	    }
	    return bmp;
	}
}
